import { createStore } from 'vuex'
import Cookies from 'js-cookie'

// 获取token的优先级：Cookie > localStorage
function getInitialToken() {
  const cookieToken = Cookies.get('token')
  const localToken = localStorage.getItem('token')
  return cookieToken || localToken || null
}

// 获取用户信息
function getInitialUserInfo() {
  const userInfoStr = Cookies.get('userInfo')
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr)
    } catch (e) {
      console.error('解析用户信息失败:', e)
      return null
    }
  }
  return null
}

export default createStore({
  state: {
    // 用户信息
    userInfo: getInitialUserInfo(),
    // 用户类型: 'user' | 'admin'
    userType: Cookies.get('userType') || null,
    // 登录token
    token: getInitialToken(),
    // 侧边栏状态
    sidebarCollapsed: false
  },
  getters: {
    // 是否已登录
    isLoggedIn: (state) => {
      return !!state.token && !!state.userInfo
    },
    // 是否是管理员
    isAdmin: (state) => {
      return state.userType === 'admin'
    },
    // 是否是普通用户
    isUser: (state) => {
      return state.userType === 'user'
    }
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      if (userInfo) {
        Cookies.set('userInfo', JSON.stringify(userInfo), { expires: 7 })
      } else {
        Cookies.remove('userInfo')
      }
    },
    // 设置用户类型
    SET_USER_TYPE(state, userType) {
      state.userType = userType
      if (userType) {
        Cookies.set('userType', userType, { expires: 7 })
      } else {
        Cookies.remove('userType')
      }
    },
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        // 同时存储到Cookie和localStorage
        Cookies.set('token', token, { expires: 7 })
        localStorage.setItem('token', token)
      } else {
        // 同时清除Cookie和localStorage
        Cookies.remove('token')
        localStorage.removeItem('token')
      }
    },
    // 切换侧边栏状态
    TOGGLE_SIDEBAR(state) {
      state.sidebarCollapsed = !state.sidebarCollapsed
    },
    // 登出
    LOGOUT(state) {
      state.userInfo = null
      state.userType = null
      state.token = null
      // 清除所有存储
      Cookies.remove('userInfo')
      Cookies.remove('userType')
      Cookies.remove('token')
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 登录
    login({ commit }, { userInfo, userType, token }) {
      commit('SET_USER_INFO', userInfo)
      commit('SET_USER_TYPE', userType)
      commit('SET_TOKEN', token)
    },
    // 登出
    logout({ commit }) {
      commit('LOGOUT')
    },
    // 更新用户信息
    updateUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    }
  }
}) 